public class EntitlementListAsset{

    List<EntitlementWrapper> entList;
    Id contId;
    
    public static String getCaseEntitlementFieldId() {
        String fldId;
        try {
            fldId = [Select Case_Entitlements_Field_Id__c From Entitlements_Settings__c].Case_Entitlements_Field_Id__c;
        } catch(Exception e) {
            fldID = '00N999999999999';
        }
        return fldId;
    }

    public static boolean HasEntForSP(Id spId) {
        return ([select count() from Entitlement__c where Support_Program__c=:spId] > 0);
    }

        public static String PadR(String s, Integer len, String padChar){
            s=s.trim();
            String newString=s;
            if(len>s.length() && len>0){
                for(Integer i=1;i<80-s.length();i++){
                    newString+=padChar;
                }
            }
            return newString;
        }
        public static String CombineSPNameAndID(String SPName, ID SPID){
            return PadR(SPName,80,' ')+'|'+SPID;
        }      
        
        public static String GetNameFromCombineSP(String spNameAndID){
            //String[] s = EntUtil.SplitSPNameAndID(spNameAndID);
            //return s[0].trim();
            String name = spNameAndID.substring(0,spNameAndID.lastIndexOf('|'));
            return name.trim();
        }
        
        public static Id GetIDFromCombineSP(String spNameAndID){
            //String[] s = EntUtil.SplitSPNameAndID(spNameAndID);
            //return (Id)s[1].trim();
            String id = spNameAndID.substring(spNameAndID.lastIndexOf('|')+1);        
            return (Id)id;
        }
        
    
    public List<EntitlementWrapper> getEntitlementList(List<Id> spId, List<Support_Program__c> acSpList,Boolean chk){
    
        contId = System.CurrentPageReference().getParameters().get('id');
        system.debug(contId);
        DateTime d = system.now();
        Date nowDate = Date.newInstance(d.Year(),d.Month(),d.Day()); 
        
        //List<EntitlementWrapper> entList = new List<EntitlementWrapper>();
        entList = new List<EntitlementWrapper>();
        
        // These two contain identical records; the set is used only for dedup
        List<EntitlementWrapper> allData = new List<EntitlementWrapper>();
        Set<Id> allDataIdSet = new Set<Id>();
        
        Boolean spIsAcLookup = False;
        for(Id id : spId){
            entList.clear();   
            spIsAcLookup = (acSpList.size()>0 && acSpList[0].Id == id);
            
            Entitlement__c[] eList;
            
            if(spIsAcLookup){
                //Get only those entitlements which have Case Pack turned off and not expired by date.
                eList = [Select e.Case_Pack__c, e.End_Date__c, e.Start_Date__c, 
                                            e.Renewal_Amount__c,e.Cases_Remaining__c, e.Business_Hours__c, 
                                            e.Name, e.Id, e.Support_Program__c, 
                                            e.Support_Program__r.Contract__c, e.Support_Program__r.Contract__r.ContractNumber, 
                                            e.Support_Program__r.Name, e.Support_Program__r.Id from Entitlement__c e 
                                            Where Support_Program__c=:id and 
                                            (e.Case_Pack__c=False) and
                                            ((e.Start_Date__c=null and e.End_Date__c=null) or (e.Start_Date__c=null and e.End_Date__c>=:nowDate) or (e.Start_Date__c<:nowDate and e.End_Date__c>:nowDate) or (e.Start_Date__c<=:nowDate and e.End_Date__c=null) or (e.Start_Date__c=:nowDate) or (e.End_Date__c=:nowDate))
                                            Order By e.Name];                
            }
            else{
                //Get entitlements which are valid
                eList = [Select e.Case_Pack__c, e.End_Date__c, e.Start_Date__c, 
                                            e.Renewal_Amount__c,e.Cases_Remaining__c, e.Business_Hours__c, 
                                            e.Name, e.Id, e.Support_Program__c, 
                                            e.Support_Program__r.Contract__c, e.Support_Program__r.Contract__r.ContractNumber, 
                                            e.Support_Program__r.Name, e.Support_Program__r.Id from Entitlement__c e 
                                            Where Support_Program__c=:id and 
                                            (e.Case_Pack__c=False or (e.Case_Pack__c=True and (e.Cases_Remaining__c>0 or e.Renewal_Amount__c>0))) and
                                            ((e.Start_Date__c=null and e.End_Date__c=null) or (e.Start_Date__c=null and e.End_Date__c>=:nowDate) or (e.Start_Date__c<:nowDate and e.End_Date__c>:nowDate) or (e.Start_Date__c<=:nowDate and e.End_Date__c=null) or (e.Start_Date__c=:nowDate) or (e.End_Date__c=:nowDate))
                                            Order By e.Name];                
            }
            
            Support_Program__c[] aList = [Select sp.Id, (Select Asset__c, Asset__r.Name, Asset__r.ContactId From sp.Program_Assets__r) from Support_Program__c sp Where sp.Id=:id];
            if(chk=true)
                AddToEntitlementList(eList, aList);
            else
                AddToEntitlementList(eList, aList);
              //  entList.add(new EntitlementWrapper(eList, null)); 
            
            
            //Add above result in main data list
            system.debug('>>>'+entList.Size()+'>>>');
            for(Integer i=0;i<entList.size();i++){
              /*  EntitlementWrapper ew = entList.get(i);
                if (!allDataIdSet.contains(ew.getEntitlement().Id)) {
                    allData.add(ew);
                   allDataIdSet.add(ew.getEntitlement().Id);                
                }*/
               allData.add(entList.get(i));
            }
        }
        system.debug(allData.Size());
        return allData;        

    }   
    
    public void AddToEntitlementList(Entitlement__c[] eList, Support_Program__c[] aList){
        for(Entitlement__c e : eList)
        {
            for(Support_Program__c sp : aList){ 
                if(sp.Program_Assets__r.Size()>0){
                    for(Program_Asset__c pa : sp.Program_Assets__r){
                        if(pa.Asset__r.ContactId==null || pa.Asset__r.ContactId==contId){
                            entList.add(new EntitlementWrapper(e, pa));                             
                        }
                    }               
                }
                else{
                    entList.add(new EntitlementWrapper(e, null)); 
                }
            }
        }
    }    
    
    public PageReference CreateNewCase(Id retUrlId, Id contId, Id acId, String prmFunc, Id prmEntId, Id prmspId, String prmEntName, Id prmAstId,String prmAstName ){
       system.debug('assetid: '+prmAstId);
       system.debug('assetid: '+prmAstName);
        String EntFieldId             = getCaseEntitlementFieldId();  //UnmanagedVersionChangeMe.CaseEntitlementFieldId;
//        String EntFirstResponseId     = '00N30000002NWq7';
//        String EntFirstWorkaroundId   = '00N30000002NWqM';
//        String EntResolveTimeId       = '00N30000002NWqJ';
        // Note:
        // The real Id consists of 18 characters. But some reason, while passing as a parameter in Url,
        // it does not seem to be accepting. If we pass whole 18 characters, 'Data Not Found' error is occurred.
        // So, while passing the parameter, only 15 characters are passed.      
        Entitlement__c selectedEntitlement = [select Id, Name, Business_Hours__c, Case_Pack__c, Cases_Remaining__c, Renewal_Amount__c from Entitlement__c where Id=:prmEntId];
               
        if(prmFunc.toLowerCase()=='addcasestoentitlement'){              
            //Renew Entitlement
            selectedEntitlement.Cases_Remaining__c = selectedEntitlement.Renewal_Amount__c;
            update selectedEntitlement;
        }
        
        String ContactId, AccountName, CaseOrigin, Status, Priority, EntId, EntFR, EntFW, EntRT,AsstId,AsstName;
        ContactId = '';
        if(contId!=null){
            ContactId = (String)contId;
            ContactId = '&cas3_lkid='+ContactId.substring(0,ContactId.length()-3);
        }
        
        String AccountId = '';
        if (acId!=null) {
            AccountId = (String)acId;
            AccountId = AccountId.substring(0,AccountId.length()-3);
            AccountId = '&cas4_lkid='+AccountId;
        }
        
        AsstId='';
        if(AsstId!=Null){
            AsstId=(string)prmAstId;
            AsstId='&def_asset_id='+AsstId.substring(0,AsstId.length()-3);
        }
      /*  String AsstI;
        AsstId=(string)prmAstId;
        if(AsstId!='02i30000001FFO5'){
           // AsstId=(string)prmAstId;
           AsstI='&def_asset_id='+AsstId.substring(0,AsstId.length()-3);
        }
        if(AsstId=='02i30000001FFO5'){
        //  AsstId=(String)prmAstId;
            String abc='02i30000001FGAu';
            AsstI='&def_asset_id='+abc;
            
        }   */
          
     
        EntId = (String)prmEntId;
        
        EntId = EntId.substring(0,EntId.length()-3);        
        EntId = '&CF'+EntFieldId+'_lkid='+EntId+'&CF'+EntFieldId+'='+getEntName(prmEntId);
      
        CaseOrigin = '&cas11='+CaseStdFieldControl.GetDefaultPicklistValueFromCase().get(CaseStdFieldControl.PICKLIST_ORIGIN);
        Status = '&cas7='+CaseStdFieldControl.GetDefaultPicklistValueFromCase().get(CaseStdFieldControl.PICKLIST_STATUS);
        Priority = '&cas8='+CaseStdFieldControl.GetDefaultPicklistValueFromCase().get(CaseStdFieldControl.PICKLIST_PRIORITY);          
        
//        EntFR = '&'+EntFirstResponseId+'=';
//        EntFW = '&'+EntFirstWorkaroundId+'=';
//        EntRT = '&'+EntResolveTimeId+'=';
        
       // Entitlement__c ent4BH = EntUtil.getSPEnt(prmEntId);     
        //Decimal efr = EntUtil.GetHourForPriority(ent4BH, sPriority, 'RESPONSE');
        //Decimal efw = EntUtil.GetHourForPriority(ent4BH, sPriority, 'WORKAROUND');
        //Decimal ert = EntUtil.GetHourForPriority(ent4BH, sPriority, 'RESOLVE');
/*        Decimal efr, efw, ert;
        try {
            EntUtil.SPEWrapper spe = new EntUtil.SPEWrapper(prmEntId);


            
            efr = spe.getEntitledTime( EntUtil.TimeType.EFR, Priority );
            efw = spe.getEntitledTime( EntUtil.TimeType.EFW, Priority );
            ert = spe.getEntitledTime( EntUtil.TimeType.ERT, Priority );
        } catch(Exception e) {
            efr = efw = ert = 0;
        }
        
        DateTime currentDate = system.now();
        Id bId = selectedEntitlement.Business_Hours__c;
        
        if(efr>0){
            DateTime dtefr = BHWithFallback.BHAdd(bId, currentDate, (efr*60*60*1000).intValue());
            EntFR += dtefr.format();
        }        
        if(efw>0){
            DateTime dtefw = BHWithFallback.BHAdd(bId, currentDate, (efw*60*60*1000).intValue());
            EntFW += dtefw.format();
        }
        if(ert>0){            
            DateTime dtert = BHWithFallback.BHAdd(bId, currentDate, (ert*60*60*1000).intValue());
            EntRT += dtert.format();
        }
*/      
         
       // AsstName=prmAstName;
      //  System.debug(AsstId);
       // system.debug(AsstName);
       
        
          PageReference    page = new PageReference('/500/e?retURL=/'+retUrlId+AsstId+ContactId+AccountId+CaseOrigin+Status+Priority+EntId); //+EntFR+EntFW+EntRT);        
        
       
        //PageReference page = new PageReference('/500300000059pd7/e?retURL=/500300000059pd7?isdtp=mn&retURL=/ui/desktop/DesktopMainDefaultPage?isdtp=mn&def_contact_id=0033000000TaD8U&def_account_id=0013000000LVxgF&isdtp=mn&saveURL=/servlet/servlet.Integration?lid=01N600000004hPk');
        page.setRedirect(true);
        return page;
        
    }   
    
    public static String getEntName(Id entId){
        return [select Name from Entitlement__c where Id=:entId].Name;
    }   
    
    public class EntitlementWrapper {
    
        Entitlement__c ent;     
        String strSPName;
        String strSPId;
        String strContRactId;
        String strContractNumber;
        
        String strAstId;
        String strAstName;
        
        //Constructor
        public EntitlementWrapper(Entitlement__c entIn, Program_Asset__c paIn){
            this.ent = entIn;
            
            if(paIn==null){
                this.strAstId = Null;
                this.strAstName =Null;
            }
            else{
                this.strAstId = paIn.Asset__c;
                this.strAstName = paIn.Asset__r.Name;
            }
                        
            system.assert( this.ent.Support_Program__c != null, 'ent<'+this.ent+'>.Support_Program__c is NULL' );
            this.strSPName = this.ent.Support_Program__r.Name;
            this.strSPId = this.ent.Support_Program__c;
            
            this.strContRactId = null;
            this.strContractNumber = 'None';
            if(ent.Support_Program__r.Contract__c!=null){
                this.strContractNumber = ent.Support_Program__r.Contract__r.ContractNumber;
                this.strContRactId = ent.Support_Program__r.Contract__c;
            }   
        }
            
        public Entitlement__c getEntitlement() {
            system.debug( '>> this.ent.Support_Program__c: '+this.ent.ENT_2__Support_Program__c );
            return ent;
        }

        public String getSPName() {
            return strSPName;
        }
        public String getSPId() {
            return strSPId;
        }  
        
        public String getAssetName(){
            return strAstName;
        }
        
        public String getAssetId(){
            return strAstId;
        }
        
        public String getContRactId() {
            return strContRactId;
        }
        public String getCasesRemaining(){
            String cr = '';     
            
            cr = ent.Cases_Remaining__c!=null?ent.Cases_Remaining__c.format():'N/A';
            cr = ent.Case_Pack__c==True?cr:'N/A';
                        
            return cr;
        }
        
        public String getContractNumber(){                      
            return strContractNumber;      
        }
        
        public String getButtonCaption(){
            String bc = '';
            String status = EntUtil.GetEntStatusForNewCase(ent);
            if(status.toLowerCase()=='new'){
                bc = 'New Case From Entitlement';
            }
            else if(status.toLowerCase()=='renew'){
                bc = 'Renew Entitlement And Create New Case';
            }
            return bc;
        }
        
        public Boolean getContractLinkMode(){
            return ent.Support_Program__r.Contract__c == null;
        }
        
        public String getNewCaseFuncName(){
            
            Double casesRemaining, renewalAmount;
            casesRemaining = ent.Cases_Remaining__c==null?0:ent.Cases_Remaining__c;
            renewalAmount = ent.Renewal_Amount__c==null?0:ent.Renewal_Amount__c;
            
            Boolean createNewCases = ent.Case_Pack__c==True && casesRemaining==0;
            String fn = '';
            if(createNewCases && renewalAmount>0){
                fn = 'addcasestoentitlement';
            }
            else if((ent.Case_Pack__c==True && casesRemaining>0) || (ent.Case_Pack__c==False)){
                fn = 'newcasefromentitlement';
            }
            
            return fn;
        }
        
        public Boolean getRendered() {
            Boolean retVal = True;
            Double casesRemaining, renewalAmount;
            casesRemaining = ent.Cases_Remaining__c==null?0:ent.Cases_Remaining__c;
            renewalAmount = ent.Renewal_Amount__c==null?0:ent.Renewal_Amount__c;
            if(ent.Case_Pack__c==True && casesRemaining==0 && renewalAmount==0){
                retVal = False;
            }
            
            return retVal;
        }
    }


    
}